<template>
  <div class="login-container">
    <!-- 头部导航 -->
    <van-nav-bar title="登录" left-arrow>
      <template #left>
        <img class="logo" src="@/assets/images/logo.png" alt="">
      </template>
    </van-nav-bar>
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field v-model="formLogin.mobile" type="tel" label="手机号" placeholder="请输入手机号" required
        :rules="[{ required: true, message: '请填写正确的手机号', trigger: 'onChange', pattern: /^1[3456789]\d{9}$/  }]" />
      <van-field v-model="formLogin.code" type="password" label="密码" placeholder="请输入密码" required
        :rules="[{ required: true, message: '请填写6位密码', trigger: 'onChange', pattern: /^\d{6}$/ }]" />
      <div style="margin: 16px;">
        <van-button block type="info" :loading="isLoding" loading-text="登录中..." native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { loginAPI } from '@/api/login'
export default {
  name: 'Login',
  data () {
    return {
      // 登录的表单数据
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      },
      // 登录按钮状态
      isLoding: false,
      ...mapMutations('user', ['setToken', 'setRefreshToken'])
    }
  },
  methods: {
    // 登录的提交函数
    async onSubmit () {
      // 切换按钮状态
      this.isLoding = true
      // 调用接口,发送请求
      const res = await loginAPI(this.formLogin)
      this.isLoding = false
      const { token, refresh_token: refreshToken } = res.data.data
      // 调用vuex保存token
      this.setToken(token)
      this.setRefreshToken(refreshToken)
      // 跳转路由
      this.$router.push('/layout')
    }
  }
}
</script>

<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
</style>
